package com.bdqn.dao;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BaseDao {
    private final static Logger log = LogManager.getLogger(BaseDao.class);
    // 数据库连接
    private static String driver = "com.mysql.cj.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/dao?serverTimezone=GMT-8";
    private static String username = "root";
    private static String password = "123456";
    static {
        loadDriver();
    }
    private static void loadDriver() {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            log.error("加载数据库驱动失败: " + e.getMessage());
        }
    }
    public Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            log.error("获取数据库连接失败: " + e.getMessage());
        }
        return conn;
    }

    public void closeAll(ResultSet rs, Statement stmt, Connection conn) {
        if (rs!= null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.error("关闭结果集失败: " + e.getMessage());
            }
        }
        if (stmt!= null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                log.error("关闭语句对象失败: " + e.getMessage());
            }
        }
        if (conn!= null) {
            try {
                conn.close();
            } catch (SQLException e) {
                log.error("关闭数据库连接失败: " + e.getMessage());
            }
        }
    }
    /**
     * 通用增删改
     *
     * @param sql
     * @param params
     * @return
     */

    public int executeUpdate(String sql, Object[] params) {
        int row = 0;
        PreparedStatement prestmt = null;
        Connection conn = getConnection();
        try {
            prestmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                prestmt.setObject(i + 1, params[i]);
            }
            row = prestmt.executeUpdate();
        } catch (SQLException e) {
            log.error("执行更新操作失败: " + e.getMessage());
        } finally {
            closeAll(null, prestmt, conn);
        }
        return row;
    }

    public <T> List<T> executeQuery(Class<T> targetType, String sql, Object... params) {
        List<T> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);
            if (pstmt!= null) {
                for (int i = 0; i < params.length; i++) {
                    if (params[i]!= null) {
                        pstmt.setObject(i + 1, params[i]);
                    }
                }
            }
            rs = pstmt.executeQuery();
            // 通过 Java 反射实现通用的数据列与实体赋值
            // 结果集列信息 Map 集合
            Map<String, String> columnMap = new HashMap<>();
            // 获取 ResultSet 对象的列的数量、类型和属性
            ResultSetMetaData metaDate = null;
            try {
                metaDate = rs.getMetaData();
            } catch (SQLException e) {
                log.error("获取结果集元数据失败: " + e.getMessage());
                return list;
            }
            // 获得查询结果集总列数
            int columnCount = 0;
            try {
                columnCount = metaDate.getColumnCount();
            } catch (SQLException e) {
                log.error("获取列数失败: " + e.getMessage());
                return list;
            }
            for (int i = 1; i <= columnCount; i++) {
                // 将列名以及对应的类型信息保存到 Map 集合中
                String columnName = null;
                String columnType = null;
                try {
                    columnName = metaDate.getColumnName(i);
                    columnType = metaDate.getColumnTypeName(i);
                } catch (SQLException e) {
                    log.error("获取列名或类型失败: " + e.getMessage());
                    continue;
                }
                columnMap.put(columnName, columnType);
            }
            // 处理结果集中的数据
            while (rs.next()) {
                // 通过反射，使用 Class<T> 构造一个对象
                T target = null;
                try {
                    target = targetType.newInstance();
                } catch (InstantiationException | IllegalAccessException e) {
                    log.error("创建对象实例失败: " + e.getMessage());
                    continue;
                }
                // 获取 Class<T> 里面所有的 public 方法
                Method[] methods = targetType.getMethods();
                if (methods!= null && methods.length > 0) {
                    for (Method method : methods) {
                        // 找到 set 前缀的方法
                        if (method.getName().startsWith("set")) {
                            // 获取方法的参数列表
                            Class<?>[] args = method.getParameterTypes();
                            // 找到只有一个参数的方法
                            if (args.length == 1) {
                                String paramName = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4);
                                if (columnMap.containsKey(paramName)) {
                                    try {
                                        Object value = parseValue(rs.getString(paramName), args[0]);
                                        method.invoke(target, value);
                                    } catch (ParseException e) {
                                        log.error("参数转换错误: " + e.getMessage());
                                    } catch (InvocationTargetException e) {
                                        log.error("方法调用目标异常: " + e.getMessage());
                                    }
                                } else if (Boolean.class == args[0] || boolean.class == args[0]) {
                                    method.invoke(target, false);
                                }
                            }
                        }
                    }
                }
                list.add(target);
            }
        } catch (SQLException e) {
            log.error("执行查询操作失败: " + e.getMessage());
        } catch (IllegalAccessException e) {
            log.error("非法访问异常: " + e.getMessage());
        } catch (InvocationTargetException e) {
            log.error("调用目标异常: " + e.getMessage());
        } finally {
            closeAll(rs, pstmt, conn);
        }
        return list;
    }

    private Object parseValue(String value, Class<?> type) throws ParseException {
        if (value == null) {
            return null;
        }
        if (Integer.class == type || int.class == type) {
            return Integer.valueOf(value);
        }
        if (Float.class == type || float.class == type) {
            return Float.valueOf(value);
        }
        if (Double.class == type || double.class == type) {
            return Double.valueOf(value);
        }
        if (String.class == type) {
            return value;
        }
        if (Date.class == type) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.parse(value);
        }
        return null;
    }
}
